import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Params from '../components/goods/Params.vue'
import GoodList from '../components/goods/List.vue'
import AddGoods from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
import Report from '../components/report/Report.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/Welcome',
    children: [
      { path: '/Welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodList },
      { path: '/goods/add', component: AddGoods },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ]
  }
]

const router = new VueRouter({ routes })

/***
 * 登录功能实现
 * 如果用户没有登录, 但直接通过url访问特定的页面, 需要重新导航到登陆页面
 * to: 表示将要访问的路径, from 从那个页面跳转过来, next放行函数
 * 退出的功能,直接销毁token就行了
 */

router.beforeEach((to, from, next) => {
  // 若果直接进入登录页面, 直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage中获取token值
  const token = sessionStorage.getItem('token')
  // next('/login') 强制执行, 没有token时
  if (!token) return next('/login')
  next()
})

export default router
